package cn.agiledata.bank.netReturn.action;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.agiledata.bank.common.dao.TransactionTemplate;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.ForeDict;
import cn.agiledata.bank.common.util.IOUtil;
import cn.agiledata.bank.common.util.WebUtil;
import cn.agiledata.bank.hibernateBean.Transaction;
import cn.agiledata.bank.linkbank.logic.payment.UnsPayResponse;
import cn.agiledata.bank.netReturn.exception.NetReturnException;
import cn.agiledata.bank.netReturn.form.NetReturnForm;
import cn.agiledata.bank.netReturn.logic.NetReturnResponse;
import cn.agiledata.bank.netReturn.service.NetReturnService;
import com.vnv.infrastructure.action.IPBBaseAction;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;

public class NetReturnRequestAction extends IPBBaseAction {

	public int hasAccessPermission(int accessLevel, HttpServletRequest request)
    throws IPBException {
		return 1;
	}
//	private FieldValidateService getFieldValidateService() {
//		return (FieldValidateService) IPBAppFactory.getObj(ForeDict.SERVICE_FIELD_VALIDATE_SERVICE);
//	}
	
	private NetReturnService getReturnMoneyService() {
        return (NetReturnService) IPBAppFactory.getObj(ForeDict.SERVICE_NET_RETURN);
    }
	
	private TransactionTemplate getTransactionTemplate() {
		return (TransactionTemplate) IPBAppFactory.getObj(ForeDict.TRANSACTION_TEMPLATE);
	}

	public ActionForward netReturnRequest(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception {
		NetReturnForm form = (NetReturnForm) actionForm;
		HttpSession session = request.getSession();
		
		NetReturnResponse netReturnResponse;
		try {
			Map parameters = WebUtil.getRequestParameters(request);
			NetReturnService netReturnService = getReturnMoneyService();
			
			String version = form.getVersion();
			netReturnService.validateVersion(version, parameters);
			
            String mac = form.getMac();
            netReturnService.validateMac(parameters, mac);
            
            List netReturnList = netReturnService.getNetReturnList(form);
            netReturnResponse = createResponse(form);
            Map transMap = netReturnService.validateNetReturn(netReturnList, form.getMerchantId());
            if (!transMap.isEmpty()) {
            	netReturnResponse.setSuccess("0");
            	request.setAttribute("netReturnResponse", netReturnResponse);
            	request.setAttribute("notExsitTrans", transMap.get("notExsitTrans"));
            	request.setAttribute("illegalTrans", transMap.get("illegalTrans"));
            	return mapping.findForward("response");
            }
            List currentList = netReturnService.getNetReturnList(form);
            String batchNo = netReturnService.createReturnApply(currentList, form.getMerchantId(), null, form.getBatchModel());
            netReturnResponse.setNetReturnList(currentList);
            netReturnResponse.setBatchNo(batchNo);
            session.setAttribute("netReturnResponse", netReturnResponse);
            netReturnResponse.setSuccess("1");
            request.setAttribute("netReturnResponse", netReturnResponse);
            session.removeAttribute("sessionAccountSummary");
            return mapping.findForward("response");
		} catch (NetReturnException e) {
			netReturnResponse = createResponse(form);
			netReturnResponse.setSuccess("0");
			netReturnResponse.setReturnMessage(e.getMessage());
			request.setAttribute("netReturnResponse", netReturnResponse);
			return mapping.findForward("response");
		}
	}
	public ActionForward netReturnMessage(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception {
		NetReturnForm form = (NetReturnForm) actionForm;
		String tranId = form.getTransId();
		Transaction trans = getTransactionTemplate().getTransactionByTranId(tranId);
		String orderId = trans.getOrderId();
		String postUrl = "";
		Map parameters = getReturnMoneyService().getParameters(trans);
		if (StringUtils.isEmpty(trans.getSellerUrl())) {
			return mapping.findForward("success");
		} else {
			try {
				if (StringUtils.isEmpty(orderId)){
					String webRootUrl = WebUtil.getRoot(request);
					postUrl = getIntegratedUrl(webRootUrl, trans.getSellerUrl());
					IOUtil.postNetReturnUrl(postUrl, parameters);
				} else {
					IOUtil.postNetReturnUrl(trans.getSellerUrl(), parameters);
				}
			} catch (RuntimeException e) {
				e.printStackTrace();
			}
			return mapping.findForward("success");
		}
	}
	
	private NetReturnResponse createResponse(NetReturnForm form){
		NetReturnResponse netReturnResponse = new NetReturnResponse();
		netReturnResponse.setAccountId(form.getMerchantId());
		netReturnResponse.setOrderId(form.getOrderNo());
		netReturnResponse.setAmount(form.getAmount());
        netReturnResponse.setMerchantUrl(form.getMerchantUrl());
        netReturnResponse.setPayModel(form.getPayModel());
        netReturnResponse.setBatchModel(form.getBatchModel());
        netReturnResponse.setMac(form.getMac());
        return netReturnResponse;
	}
	
	private String getIntegratedUrl(String webRootUrl, String relativeUrl) {
        if (webRootUrl.endsWith("/")) {
            webRootUrl = webRootUrl.substring(0, webRootUrl.length() - 1);
        }
        if (!relativeUrl.startsWith("/")) {
            relativeUrl += "/" + relativeUrl;
        }
        return webRootUrl + relativeUrl;
    }

}
